package com.github.iot.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.github.iot.R;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.NetPattern;
import com.github.iot.entity.NetServer;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.utils.CommonUtils;
import com.github.iot.utils.ConvertHexUtils;
import com.github.iot.utils.KeyboardUtils;
import com.github.iot.utils.ToastUtils;
import com.github.iot.utils.WifiUtils;
import com.github.iot.view.RxTitle;
import com.github.iot.view.dialogs.fragment.ListDialogFragment;
import com.github.iot.view.dialogs.fragment.SimpleDialogFragment;
import com.github.iot.view.dialogs.iface.IListDialogListener;
import com.github.iot.view.dialogs.iface.ISimpleDialogListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/12 9:42
 * @Version: v1.0.0
 */
public class NetSettingActivity extends AppCompatActivity implements IListDialogListener, ISimpleDialogListener {

    @BindView(R.id.rx_title)
    RxTitle mTitle;

    @BindView(R.id.iv_conn)
    AppCompatImageView mIvConn;

    @BindView(R.id.tv_wifi)
    AppCompatTextView mTvWifi;

    @BindView(R.id.tv_conn)
    AppCompatTextView mConnServer;

    @BindView(R.id.et_pattern)
    AppCompatEditText mPattern;

    @BindView(R.id.et_wifi_name)
    AppCompatEditText mWifiName;

    @BindView(R.id.et_wifi_password)
    AppCompatEditText mWifiPassword;

    @BindView(R.id.et_server_ip)
    AppCompatEditText mServerIp;

    @BindView(R.id.et_server_port)
    AppCompatEditText mServerPort;

    @BindView(R.id.et_server_mask)
    AppCompatEditText mServerMask;

    private static NetPattern netPattern;
    private static Integer pattern = 2;

    private static final int REQUEST_LIST_SIMPLE = 11;
    private static final int REQUEST_SIMPLE_DIALOG = 22;
    private static final int REQUEST_WIFI_DIALOG = 33;
    private static final int REQUEST_NET_SERVER = 44;

    private static CommonDaoUtils<NetPattern> netPatternDaoUtils = DaoUtilsStore.getInstance().getNetPatternDaoUtils();
    private static CommonDaoUtils<NetServer> netServerDaoUtils = DaoUtilsStore.getInstance().getNetServerDaoUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_net_setting);

        ButterKnife.bind(this);

        initView();
        initData();

        isWifiConn();
    }

    private void initView() {
        mTitle.setLeftFinish(this);
        mTitle.setRightTextOnClickListener(v -> ActivityUtils.skipActivity(NetSettingActivity.this, NetServerActivity.class));
        mPattern.setFocusable(false);
    }

    private void initData() {
        List<NetPattern> list = netPatternDaoUtils.queryAll();
        if (list.size() > 0) {
            netPattern = list.get(0);
            pattern = netPattern.getPattern();

            mWifiName.setText(netPattern.getWifiName());
            mWifiPassword.setText(netPattern.getWifiPassword());
            mServerIp.setText(netPattern.getServerIp());
            mServerPort.setText(String.valueOf(netPattern.getServerPort()));
            mServerMask.setText(netPattern.getServerMask());

            if (pattern == 1) {
                mPattern.setText("模式1");
            } else if (pattern == 2) {
                mPattern.setText("模式2");
            } else if (pattern == 3) {
                mPattern.setText("模式2");
            }
        }
    }

    private void setNetPattern() {
        String pattern1 = mPattern.getText().toString();
        String wifiName = mWifiName.getText().toString();
        String wifiPassword = mWifiPassword.getText().toString();
        String serverIp = mServerIp.getText().toString();
        String serverPort = mServerPort.getText().toString();
        String serverMask = mServerMask.getText().toString();

        if (TextUtils.isEmpty(pattern1)) {
            ToastUtils.warning("请选择网络模式");
            return;
        }

        if (TextUtils.isEmpty(wifiName)) {
            ToastUtils.warning("WIFI名称不能为空");
            return;
        }

        if (TextUtils.isEmpty(wifiPassword)) {
            ToastUtils.warning("WIFI密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(serverIp)) {
            ToastUtils.warning("服务端IP不能为空");
            return;
        }

        if (!CommonUtils.isIp(serverIp)) {
            ToastUtils.warning("服务端IP输入有误！");
            return;
        }

        if (TextUtils.isEmpty(serverPort)) {
            ToastUtils.warning("服务端端口不能为空");
            return;
        }

        if (Integer.valueOf(serverPort) >= 65535 || Integer.valueOf(serverPort) <= 0) {
            ToastUtils.warning("服务端端口输入有误！");
            return;
        }

        if (TextUtils.isEmpty(serverMask)) {
            ToastUtils.warning("服务端子网掩码不能为空");
            return;
        }

        if (null != netPattern) {
            netPattern.setPattern(pattern);
            netPattern.setWifiName(wifiName);
            netPattern.setWifiPassword(wifiPassword);
            netPattern.setServerIp(serverIp);
            netPattern.setServerPort(Integer.valueOf(serverPort));
            netPattern.setServerMask(serverMask);

            boolean flag = netPatternDaoUtils.update(netPattern);
            if (flag) {
                sendMessage(netPattern);
            } else {
                ToastUtils.error("网络模式设置失败");
            }
        } else {
            netPattern = new NetPattern();
            netPattern.setPattern(pattern);
            netPattern.setWifiName(wifiName);
            netPattern.setWifiPassword(wifiPassword);
            netPattern.setServerIp(serverIp);
            netPattern.setServerPort(Integer.valueOf(serverPort));
            netPattern.setServerMask(serverMask);

            long i = netPatternDaoUtils.insert(netPattern);
            if (i > 0) {
                sendMessage(netPattern);
            } else {
                ToastUtils.error("网络模式设置失败");
            }
        }
    }

    /**
     * 判断是否是wifi
     */
    private void isWifiConn() {
        if (!WifiUtils.isWiFiActive(NetSettingActivity.this)) {
            SimpleDialogFragment.createBuilder(NetSettingActivity.this, getSupportFragmentManager())
                    .setTitle("系统提示")
                    .setMessage("目前没有连接WIFI, 是否打开WIFI连接！")
                    .setPositiveButtonText("确定")
                    .setNegativeButtonText("取消")
                    .setCancelable(false)
                    .setRequestCode(REQUEST_WIFI_DIALOG)
                    .show();
            return;
        }
    }

    /**
     * 发送网络设置指令
     *
     * @param np
     */
    private void sendMessage(NetPattern np) {
        byte[] headByte = new byte[4];
        if (np.getPattern() == 1) {
            headByte = new byte[]{(byte) 0xff, (byte) 0x00, (byte) 0x01, (byte) 0x00};
        } else if (np.getPattern() == 2) {
            headByte = new byte[]{(byte) 0xff, (byte) 0x00, (byte) 0x01, (byte) 0x02};
        } else if (np.getPattern() == 3) {
            headByte = new byte[]{(byte) 0xff, (byte) 0x00, (byte) 0x01, (byte) 0x03};
        }

        byte[] nameByte = byteLength(np.getWifiName().getBytes());
        byte[] passByte = byteLength(np.getWifiPassword().getBytes());
        byte[] ipByte = byteLength(np.getServerIp().getBytes());
        byte[] portByte = byteLength(String.valueOf(np.getServerPort()).getBytes());
        byte[] maskByte = byteLength(np.getServerMask().getBytes());

        byte[] b = ConvertHexUtils.byteMergerAll(headByte, nameByte, passByte, ipByte, portByte, maskByte);
        byte[] crc = ConvertHexUtils.convert16HexToByte(ConvertHexUtils.getCrc(b));
        b = ConvertHexUtils.byteMergerAll(b, crc);
    }

    /**
     * 固定长度 20
     *
     * @param b
     * @return
     */
    private static byte[] byteLength(byte[] b) {
        byte[] b1 = new byte[20];
        for (int i = 0; i < b.length; i++) {
            b1[i] = b[i];
        }
        return b1;
    }

    @OnClick({R.id.et_pattern, R.id.btn_net_setting, R.id.tv_conn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_pattern:
                ListDialogFragment
                        .createBuilder(NetSettingActivity.this, getSupportFragmentManager())
                        .setTitle("请选择网络模式")
                        .setItems(new String[]{"模式1", "模式2", "模式3"})
                        .setCancelable(false)
                        .setRequestCode(REQUEST_LIST_SIMPLE)
                        .show();
                break;
            case R.id.btn_net_setting:
                KeyboardUtils.hideSoftInput(NetSettingActivity.this);
                SimpleDialogFragment.createBuilder(NetSettingActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage("您确定要保存并下发吗？")
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setCancelable(false)
                        .setRequestCode(REQUEST_SIMPLE_DIALOG)
                        .show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        if (requestCode == REQUEST_LIST_SIMPLE) {
            if (requestCode == REQUEST_LIST_SIMPLE) {
                mPattern.setText(value);
                if ("模式1".equals(value)) {
                    pattern = 1;
                } else if ("模式2".equals(value)) {
                    pattern = 2;
                } else if ("模式3".equals(value)) {
                    pattern = 3;
                }
            }
        }
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {

    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {

    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        if (requestCode == REQUEST_SIMPLE_DIALOG) {
            setNetPattern();
        } else if (requestCode == REQUEST_WIFI_DIALOG) {
            Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
            startActivity(intent);
        } else if (requestCode == REQUEST_NET_SERVER) {
            ActivityUtils.skipActivity(NetSettingActivity.this, NetServerActivity.class);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}